using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Rensoft.Server.Security;
using System.Data.SqlClient;
using Rensoft.Server.IIS;

public class Client
{
    private int clientId;
    private string guid;

    public int ClientId
    {
        get { return clientId; }
    }

    public string Guid
    {
        get { return guid; }
    }

    /// <summary>
    /// Parameterless constructor for serialization.
    /// </summary>
    public Client() { }

    protected Client(int clientId, string guid)
    {
        this.clientId = clientId;
        this.guid = guid;
    }

    internal static Client Create(string guid, string fullName, string username, string password)
    {
        int clientId;
        using (SqlConnection connection = new SqlConnection(Settings.ConnectionStrings.HostingDatabase))
        {
            SqlCommand command = new SqlCommand("ClientCreate", connection);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.AddWithValue("guid", guid);
            command.Parameters.Add("clientId", SqlDbType.Int).Direction = ParameterDirection.Output;

            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();

            clientId = (int)command.Parameters["clientId"].Value;
        }

        WindowsUser systemUser = new WindowsUser(
            username, password, fullName,
            string.Format(Settings.Client.SystemUserDescriptionFormat, fullName),
            Settings.Client.DefaultUserFlags);

        VirtualServerManager vsManager = new VirtualServerManager(Settings.ServerName);

        WindowsUser iusrUser = new WindowsUser(
            Settings.Client.AnonymousUserPrefix + username,
            vsManager.IusrPassword,
            Settings.Client.AnonymousUserFullName,
            Settings.Client.AnonymousUserDescription,
            Settings.Client.DefaultUserFlags);

        WindowsUser iwamUser = new WindowsUser(
            Settings.Client.WorkerProcessUserPrefix + username, 
            vsManager.IwamPassword,
            Settings.Client.WorkerProcessUserFullName,
            Settings.Client.WorkerProcessUserDescription,
            Settings.Client.DefaultUserFlags,
            new WindowsUserGroup("IIS_WPG"));

        WindowsUserManager manager = new WindowsUserManager(Settings.ServerName);
        manager.Create(systemUser);
        manager.Create(iusrUser);
        manager.Create(iwamUser);

        return new Client(clientId, guid);
    }
}